<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button  type="primary"  icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['maker:config:add']" >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="roleList">
      <el-table-column label="编号" prop="id" width="120" />
      <el-table-column label="面额(元)" prop="denomination" :show-overflow-tooltip="true" width="150" >
        <template slot-scope="scope">
          <span>{{ formatCurrency(scope.row.denomination) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="type" width="180">
        <template slot-scope="scope">
          <el-tag  v-if="scope.row.type==1">现金券</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="有效时长(天)" prop="duration" width="120" />

      <el-table-column label="状态" align="center" width="120">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"  active-color="#13ce66" inactive-color="#ff4949" active-value="1"  inactive-value="0" @change="handleStatusChange(scope.row)" ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{dateFormat(scope.row.createtime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['maker:config:edit']" >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['maker:config:remove']" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"  :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="面额(元)" prop="denomination">
          <el-input v-model="form.denomination" placeholder="请输入面额(单位：元)" />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 380px" >
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="时长(天)" prop="duration">
          <el-input v-model="form.duration" placeholder="有效时长(单位:天)" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statuOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listConfig, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus } from "@/api/maker/config";
  //import { isInteger } from "@/utils/validate";


  export default {
    data() {
      let validateArgs = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('输入不可以为空'));
        }
        const re = /^[0-9]*[1-9][0-9]*$/;
        const rsCheck = re.test(value);
        if (!rsCheck) {
          return callback(new Error('请输入正整数'));
        } else {
          if(value>1000){
            return callback(new Error('超过设定范围'));
          }
          return callback();
        }
      };
      return {
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 角色表格数据
        roleList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statuOptions: [],
        typeOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          denomination: undefined,
          type: undefined,
          status: undefined
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          denomination: [
            { required: true, message: "面额不能为空", trigger: "blur" },
            { validator: validateArgs, trigger:"blur" }
          ],
          type: [
            { required: true, message: "类型不能为空", trigger: "blur" }
          ],
          duration: [
            { required: true, message: "时长不能为空", trigger: "blur" },
            { validator: validateArgs, trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_maker_disable").then(response => {
        this.statuOptions = response.data;
      });
      this.getDicts("sys_maker_type_disable").then(response => {
        this.typeOptions = response.data;
      });
    },
    methods: {
      /** 查询角色列表 */
      getList() {
        this.loading = true;
        listConfig(this.addDateRange(this.queryParams, this.dateRange)).then(
          response => {
            this.roleList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 状态修改
      handleStatusChange(row) {
        let text = row.status === "1" ? "启用" : "停用";
        //console.log(row);
        this.$confirm('确认要"' + text + '"面额为"【' + row.denomination + '】"的配置吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeRoleStatus(row.id, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        if (this.$refs.tree != undefined) {
          this.$refs.tree.setCheckedKeys([]);
        }
        this.form = {
          id: undefined,
          denomination: undefined,
          type: "1",
          duration: undefined,
          status: "1"
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        //this.getMenuTreeselect();
        this.open = true;
        this.title = "添加选项";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        getRole(row.id).then(response => {
          this.form = response.data;
          console.log(response.data);
          this.open = true;
          this.title = "修改选项";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateRole(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addRole(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 提交按钮（数据权限） */
      submitDataScope: function() {
        if (this.form.id != undefined) {
          dataScope(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.openDataScope = false;
              this.getList();
            } else {
              this.msgError(response.msg);
            }
          });
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除面额为"【' + row.denomination + '元】"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRole(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      }
    }
  };
</script>
